package study.mybatis.springboot.support.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import study.mybatis.springboot.support.utils.PluginUtils;

import java.lang.reflect.Method;
import java.sql.PreparedStatement;
import java.util.Properties;

@Slf4j
@Intercepts({
        @Signature(type = ParameterHandler.class,
                method = "setParameters",
                args = PreparedStatement.class),
})
public class ParameterInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        PluginUtils.printInvocation(invocation);

        //目标对象
        Object target = invocation.getTarget();
        ParameterHandler parameterHandler = (ParameterHandler) target;
        //代理方法
        Method method = invocation.getMethod();
        //方法参数
        Object[] args = invocation.getArgs();
        PreparedStatement ps = (PreparedStatement) args[0];

        //执行完上面的任务后，不改变原有的sql执行过程
        Object result = invocation.proceed();
        return result;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
